﻿namespace EyeOpen.Trial.Service
{
	using System;
	using System.Linq;
	using System.ServiceModel.Activation;
	using System.Web.Mvc;

	using EyeOpen.Trial.Data;

	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	public class ApplicationService
		: IApplicationService
	{
		private readonly IApplicationUnitOfWork applicationContext;

		public ApplicationService(IApplicationUnitOfWork applicationContext)
		{
			this.applicationContext = applicationContext;
		}

		public ApplicationService()
			: this(DependencyResolver.Current.GetService<IApplicationUnitOfWork>())
		{
		}

		public bool IsValid(string serial)
		{
			using (applicationContext)
			{
				var application =
					applicationContext
					.ApplicationRepository
					.SingleOrDefault(x => x.Serial == serial);

				if (application == null)
				{
					return false;
				}

				if (!application.ExpirationDate.HasValue)
				{
					application.ExpirationDate = DateTime.Now.Date;
					applicationContext.ApplicationRepository.Update(application);
					applicationContext.Commit();
				}

				return
					
					application.ExpirationDate.Value.Subtract(DateTime.Now.Date).TotalDays <= 14;
			}
		}
	}
}